<?php

namespace Lib\Controller;

use StdClass,
    Lib\Util\Session,
    Lib\Controller\Controller,
    Lib\Util\Util,
    App\Model\User;

class Auth {

    private $excludedActions = array('login', 'logout');
    private $controller;

    private static $inst;
    private static function getInstance(Controller $controller) {
        if (! self::$inst) self::$inst = new self($controller);
        return self::$inst;
    }

    public function __construct(Controller $controller) {
        $this->controller = $controller;
    }

    public static function secure(Controller $controller) {
        $auth = self::getInstance($controller);

        if ($auth->actionOverride()) {
            switch($auth->controller->action) {
                case 'logout':
                    break;

                default:
                    if (! self::authorized()) {
                        $controller->redirect('/admin/login');
                    }
                    break;
            }
        }
    }

    public static function authorized() {
        $user = Session::read('Auth.user');
        $authorized = empty($user) ? false : true;
        return $authorized;
    }

    public static function authorize(Controller $controller, StdClass $data) {
        $User = $controller->loadModel('User');
        $user = $User->addCondition('User.email', $data->email)
                      ->first();
        
        if ($user && $user['password'] == self::hash($data->password)) {
            Session::write('Auth.user', $user);
            return true;
        }

        return false;
    }

    public static function unauthorize() {
        Session::delete('Auth.user');
    }

    public static function hash($passwordString) {
        return sha1($passwordString);
    }

    private function actionOverride() {
        return !in_array($this->controller->action, $this->excludedActions);
    }
}